package com.dy.分类.链表.相交链表;


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        int lenA = len(headA);
        int lenB = len(headB);
        int cha = Math.abs(lenA - lenB);
        ListNode pA = headA;
        ListNode pB = headB;
        if (lenA > lenB) {
            while (cha > 0) {
                pA = pA.next;
                cha--;
            }
        } else {
            while (cha > 0) {
                pB = pB.next;
                cha--;
            }
        }
        while (pA != null) {
            if (pA.equals(pB)) return pA;
            pA = pA.next;
            pB = pB.next;
        }
        return null;
    }

    int len(ListNode head) {
        int count = 0;
        ListNode p = head;
        while (p != null) {
            p = p.next;
            count++;
        }
        return count;
    }
    //双指针
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode pA = headA, pB = headB;
        while (pA != pB) {
            pA = pA == null ? headB : pA.next;
            pB = pB == null ? headA : pB.next;
        }
        return pA;
    }

}